package com.novel.service;


import com.novel.common.exception.CustomerException;
import com.novel.mapper.ChapterOrderMapper;
import com.novel.mapper.NovelChapterMapper;
import com.novel.mapper.NovelMapper;
import com.novel.common.vo.Chapter;
import com.novel.pojo.novel.Novel;
import com.novel.pojo.novel.NovelChapter;
import com.novel.pojo.system.ChapterOrder;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.session.RowBounds;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.util.*;
import java.util.stream.Collectors;

@Service
@Transactional
public class NovelChapterService {

    @Autowired
    private NovelChapterMapper mapper;

    @Autowired
    private NovelMapper novelMapper;

    @Autowired
    private ChapterOrderMapper chapterOrderMapper;


    /**
     * 根据用户id查询用户所有可以阅读和下载的章节
     */
    public List<NovelChapter> findChapterByUserId(String userId, String novelId) {
        Example example = new Example(NovelChapter.class);
        example.setOrderByClause("novel_order asc");
        example.createCriteria().andEqualTo("novelId", novelId);
        List<NovelChapter> chapterList = mapper.selectByExample(example);

        List<NovelChapter> vipChapterList = chapterList.stream().filter(v -> v.getVip() == 1).collect(Collectors.toList());
        List<NovelChapter> normalChapterList = chapterList.stream().filter(v -> v.getVip() == 0).collect(Collectors.toList());

        if (CollectionUtils.isEmpty(vipChapterList)) {
            return normalChapterList;
        }

        //判断VIP章节有那些可以下载
        Example chapterOrderExample = new Example(ChapterOrder.class);
        chapterOrderExample.createCriteria()
                .andEqualTo("userId", userId)
                .andIn("chapterId", vipChapterList.stream().map(NovelChapter::getChapterId).collect(Collectors.toList()));
        List<ChapterOrder> hasChapterList = chapterOrderMapper.selectByExample(chapterOrderExample);

        //把所有章节统计返回
        List<NovelChapter> resultList = new ArrayList<>();
        resultList.addAll(normalChapterList);
        List<String> hashChapterIds = hasChapterList.stream().map(ChapterOrder::getChapterId).collect(Collectors.toList());
        resultList.addAll(vipChapterList.stream().filter(v -> hashChapterIds.contains(v.getChapterId())).collect(Collectors.toList()));

        resultList.stream().sorted(Comparator.comparing(NovelChapter::getNovelOrder));
        return resultList;
    }


    /**
     * 根据章节id查询章节内容
     *
     * @param chapterId 小说id
     */
    public Chapter findChapterById(String chapterId) {
        //查询小说章节内容信息
        NovelChapter novelChapter = mapper.selectByPrimaryKey(chapterId);
        //查询小说作者信息
        Novel novel = novelMapper.selectByPrimaryKey(novelChapter.getNovelId());
        //封装小说信息
        return new Chapter(novel, novelChapter);
    }

    /**
     * 根据小说id查询章节列表
     *
     * @param novelId 小说id
     */
    public List<NovelChapter> findChapterList(String novelId) {
        return mapper.findChapterList(novelId);
    }

    /**
     * 查询小说章节全部内容，用于小说下载
     *
     * @param novelId 小说id
     */
    public List<NovelChapter> findAllChapter(String novelId) {
        Example example = new Example(NovelChapter.class);
        example.setOrderByClause("novel_order asc");
        example.createCriteria().andEqualTo("novelId", novelId);
        return mapper.selectByExample(example);
    }

    /**
     * 添加章节内容
     * 1.保存封装好的章节内容
     * 2.同步小说的最后更新时间
     * 3.小说的id，需要封装到对象中
     *
     * @param novelChapter 小说章节对象
     */
    @Transactional
    public boolean addChapter(NovelChapter novelChapter) {
        //查询小说信息
        Novel record = novelMapper.selectByPrimaryKey(novelChapter.getNovelId());
        record.setWords(record.getWords() + novelChapter.getChapterContent().length());
        record.setLastTime(new Date());

        //更新小说信息
        int count = novelMapper.updateByPrimaryKey(record);

        if (count != 1) {
            throw new CustomerException("章节更新失败");
        }

        //封装章节信息
        novelChapter.setChapterId(UUID.randomUUID().toString());
        novelChapter.setCreateTime(new Date());

        //查询小说章节信息
        Example example = new Example(NovelChapter.class);
        example.selectProperties("novelOrder");
        example.setOrderByClause("novel_order desc limit 1");
        example.createCriteria().andEqualTo("novelId", novelChapter.getNovelId());
        NovelChapter lastChapter = mapper.selectOneByExample(example);

        //设置章节排序
        if (lastChapter == null) {
            novelChapter.setNovelOrder(1);
        } else {
            novelChapter.setNovelOrder(lastChapter.getNovelOrder() + 1);
        }

        if (mapper.insert(novelChapter) != 1) {
            throw new CustomerException("章节更新失败");
        }
        return true;
    }

    /**
     * 跳转到小说阅读界面
     *
     * @param novelId      小说id
     * @param chapterOrder 章节序号
     */
    public NovelChapter findChapterByNovelAndOrder(String novelId, Integer chapterOrder) {

        NovelChapter record = new NovelChapter();

        record.setNovelId(novelId);
        record.setNovelOrder(chapterOrder);

        List<NovelChapter> list = mapper.select(record);
        if (list.size() > 0) {
            return list.get(0);
        } else {
            return null;
        }
    }
}
